﻿using MslDiary.BLL;
using MslDiary.Enum;
using MslDiary.Framework.IO;
using MslDiary.Model;
using MslDiary.Utils;
using HtmlEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using MFW = MslDiary.Framework;
using System.Windows.Forms;
using MslDiary.Framework.Text;
using MslDiary.Framework;

namespace MslDiary.ViewModel
{
    public class DiaryListViewModel : MslDiary.Framework.ViewModelBase
    {
        private View.AddAttachFile frmAttachFile = null;
        private View.EditorSkinList frmEditorSkinList = null;// new View.EditorSkinList();

        private System.Windows.Window win;
        private A_DiaryBLL diaryBLL = new A_DiaryBLL();
        private A_ItemBLL itemBLL = new A_ItemBLL();
        private A_AnnexBLL annexBLL = new A_AnnexBLL();
        private string historyWhere = String.Empty;
        private DispatcherTimer timer;
        private Hashtable treeNodeTable;

        private const string PACK_APPLICATION = "pack://application:,,,/MslDiary;component";
        private const string EDITOR_DEFAULT_IMAGE = "/Theme/Images/EditorSkin/default.jpg";
        public DiaryListViewModel()
        {
            #region 初始化
            OnInit();
            #endregion
            #region 添加日记

            this.AddDiaryCommand = new CommandBase((Object m) =>
            {
                if (diaryBLL.IsExists(DateTime.Now))
                {
                    MslDiary.Utils.Helper.Instance.AlertWarning("今日已添加日记，若要选择其它日期，请点击左侧日历！");
                    return;
                }
                Reset(DateTime.Now);
            });
            #endregion
            #region 添加附件

            this.AddAttachFileCommand = new CommandBase((Object m) =>
            {
                //if (this.frmAttachFile == null)
                this.frmAttachFile = new View.AddAttachFile();
                if (this.DiaryModel == null)
                {
                    MslDiary.Utils.Helper.Instance.AlertWarning("请先添加日记！");
                    return;
                }
                this.frmAttachFile.lblFromRecordId.Content = this.DiaryModel.Id;
                this.frmAttachFile.Owner = this.win;
                this.frmAttachFile.ShowDialog();
                if (this.frmAttachFile.State == null)
                    return;

                if (this.frmAttachFile.State.Equals("1") || this.frmAttachFile.State.Equals("2"))
                {
                    this.IsShowAttachButton = true;
                    this.IsCheckedAttachButton = true;
                    this.DiaryAttachList = annexBLL.GetDiaryAttachList(this.DiaryModel.Id);
                    if (this.DiaryModel.Id > 0)
                        UpdateDiaryList(this.DiaryModel, false);
                }
            });
            #endregion
            #region 变化日记背景

            this.SwitchSkinCommand = new CommandBase((Object window) =>
            {
                if (frmEditorSkinList == null)
                {
                    this.frmEditorSkinList = new View.EditorSkinList();
                    this.frmEditorSkinList.Owner = this.win;
                }
                this.frmEditorSkinList.Show();
            });
            #endregion
            #region 加载日记列表

            this.ListLoadCommand = new CommandBase((Object window) =>
            {
                if (window != null)
                    this.win = (System.Windows.Window)window;

                this.IsSelectedRecycleSite = false;
                if (this.DiaryList == null || this.DiaryList.Count == 0)
                    Load("1");
            });
            #endregion
            #region 保存

            this.SaveDiaryCommand = new CommandBase((Object m) =>
            {
                RichTextEditor editor = m as RichTextEditor;
                if (m == null)
                {
                    MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.SYS_MSG01);
                    return;
                }
                this.IsSelectedRecycleSite = false;
                this.DiaryXaml = editor.Xaml;
                Save(editor.Images);
            });
            #endregion
            #region 显示/隐藏 左侧面板

            this.ShowOrShrinkLeftSPCommand = new CommandBase((Object m) =>
            {
                this.LeftStackPanelShow = !this.LeftStackPanelShow;
                this.ShowLeftSPImagePath = this.LeftStackPanelShow ? "/Theme/Images/frm_left_show.png" : "/Theme/Images/frm_left_hide.png";
            });
            #endregion
            #region 排序

            this.DiarySortMenuCommand = new CommandBase((Object m) =>
            {
                if (m == null || m.ToString().Length == 0) return;
                if (MFW.Gloable.IsImmediatelyLock) return;

                string sortBy = m.ToString();
                this.IsCheckedModifyDate = this.IsCheckedDiaryDate = this.IsCheckedCreateDate = false;
                switch (sortBy)
                {
                    case "ModifyDate": this.IsCheckedModifyDate = true; break;
                    case "DiaryDate": this.IsCheckedDiaryDate = true; break;
                    case "CreateDate": this.IsCheckedCreateDate = true; break;
                }
                Utils.Helper.Instance.Loading(() =>
                {
                    sortBy += " DESC ";
                    int recordCount = 0;
                    this.DiaryList = new ObservableCollection<A_Diary>(
                        diaryBLL.GetPageListByHistoryWhere(historyWhere, 50, 1, sortBy, out recordCount)
                    );
                }, MslDiary.Framework.ShowMessage.SEARCH_MSG01);
            });
            #endregion
            #region 搜索 日前支持“标题”模糊搜索
            //this.DiarySearchByInputChangedCommand = new CommandBase((Object m) =>
            //{
            //    if (MFW.Gloable.IsImmediatelyLock) return;
            //    if (m == null || m.ToString().Length == 0)
            //    {
            //        return;
            //    }
            //    SearchDiaryList(m.ToString());
            //});
            this.DiarySearchByInputCommand = new CommandBase((Object m) =>
            {
                if (MFW.Gloable.IsImmediatelyLock) return;
                if (m == null || m.ToString().Length == 0)
                {
                    MslDiary.Utils.Helper.Instance.Alert(MslDiary.Framework.ShowMessage.SEARCH_MSG02);
                    return;
                }
                SearchDiaryList(m.ToString());
            });
            #endregion
            #region 回收站

            this.SelectedRecycleDiaryCommand = new CommandBase((Object m) =>
            {
                if (MFW.Gloable.IsImmediatelyLock) return;
                this.IsSelectedRecycleSite = true;
                Utils.Helper.Instance.Loading(() =>
                 {
                     GetDiaryList(null, SearchType.All, null);
                 }, MslDiary.Framework.ShowMessage.SEARCH_MSG01);
            });
            #endregion
            #region 日期归档查询

            this.SelectedDateChangedCommand = new CommandBase((Object m) =>
            {
                this.IsSelectedRecycleSite = false;
                this.annexBLL.DeleteNoSaveDiaryAttach();
                //时间归档查询
                SearchByDateChanged(m);
            });
            #endregion
            #region 日记被选中

            this.DiarySelectedChangedCommand = new CommandBase((Object m) =>
            {
                if (m == null) return;
                if (MFW.Gloable.IsImmediatelyLock) return;
                A_Diary mod = (A_Diary)(m);

                //this.currentSelectedId = mod.Id;
                this.annexBLL.DeleteNoSaveDiaryAttach();
                this.DiaryModel = diaryBLL.GetModelById(mod.Id);
                UpdateDiaryXaml();
                this.ButtonAcceptText = "更新";
            });
            #endregion
            #region 选中附件

            this.AttachSelectedChangedCommand = new CommandBase((Object m) =>
            {
                if (m == null) return;
                this.SelectedAttachId = (m as A_Annex).Id;
            });
            #endregion
            #region 日历选择

            this.CalendarMouseClickCommand = new CommandBase((Object m) =>
            {
                if (m == null) return;
                CalendarClick(m.ToString());
            });
            #endregion
            this.DiaryListContextMenuCommand = new CommandBase((Object m) => DiaryListContextClick(m.ToString()));
            this.AttachSelectedContextMenuCommand = new CommandBase((Object m) => AttachListContextClick(m.ToString()));
        }
        #region 属性
        private int selectedNodeId = 0;//当前选中树Id
        private bool _isSelectedRecycleSite = false;//是否选中回收站
        private bool _isShowAttachButton = false;
        private bool _isCheckedAttachButton = false;
        private string _buttonAcceptText = "添加";
        private string _wordCountText;
        private string _nowDetailDate;
        private bool _leftStackPanelShow = true;
        private bool _isCheckedModifyDate = false;
        private bool _isCheckedDiaryDate = true;
        private bool _isCheckedCreateDate = false;
        private DateTime _diaryDate = DateTime.Now;
        private A_Diary _diaryModel;
        private List<A_Item> _weatherList;
        private List<A_Item> _moodList;
        private List<A_Annex> _diaryAttachList;
        private ObservableCollection<A_Diary> _diaryList;
        private List<TreeNodeViewModel> _dateTreeNodeList;
        private string _showLeftSPImagePath = "/Theme/Images/frm_left_show.png";
        private DiaryDisplay _diaryDisplyMode = 0;//摘要
        private int _recycleDiaryCount = 0;
        private string _diaryXaml;
        private string _editorBackGroundPath;
        /// <summary>
        /// 
        /// </summary>
        public bool IsCheckedCreateDate
        {
            get { return _isCheckedCreateDate; }
            set
            {
                if (this._isCheckedCreateDate == value)
                    return;
                this._isCheckedCreateDate = value;
                this.RaisePropertyChanged("IsCheckedCreateDate");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public bool IsCheckedModifyDate
        {
            get { return _isCheckedModifyDate; }
            set
            {
                if (this._isCheckedModifyDate == value)
                    return;
                this._isCheckedModifyDate = value;
                this.RaisePropertyChanged("IsCheckedModifyDate");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public bool IsCheckedDiaryDate
        {
            get { return _isCheckedDiaryDate; }
            set
            {
                if (this._isCheckedDiaryDate == value)
                    return;
                this._isCheckedDiaryDate = value;
                this.RaisePropertyChanged("IsCheckedDiaryDate");
            }
        }
        /// <summary>
        /// 选中的附件Id
        /// </summary>
        public int SelectedAttachId { get; set; }
        /// <summary>
        /// 编辑器背景图路径
        /// </summary>
        public string EditorBackGroundPath
        {
            get { return _editorBackGroundPath; }
            set
            {
                //base.SetProperty<string>(ref this._editorBackGroundPath, value);
                if (this._editorBackGroundPath == value)
                    return;
                this._editorBackGroundPath = value;
                this.RaisePropertyChanged("EditorBackGroundPath");
            }
        }
        /// <summary>
        /// 日记正文附件按钮是否被选中
        /// </summary>
        public bool IsCheckedAttachButton
        {
            get { return _isCheckedAttachButton; }
            set
            {
                //base.SetProperty<bool>(ref this._isShowAttachButton, value);
                if (this._isCheckedAttachButton == value)
                    return;
                this._isCheckedAttachButton = value;
                this.RaisePropertyChanged("IsCheckedAttachButton");
            }
        }
        /// <summary>
        /// 是否显示底部附件按钮
        /// </summary>
        public bool IsShowAttachButton
        {
            get { return _isShowAttachButton; }
            set
            {
                //base.SetProperty<bool>(ref this._isShowAttachButton, value);
                if (this._isShowAttachButton == value)
                    return;
                this._isShowAttachButton = value;
                this.RaisePropertyChanged("IsShowAttachButton");
            }
        }
        /// <summary>
        /// 日记附件列表
        /// </summary>
        public List<A_Annex> DiaryAttachList
        {
            get { return _diaryAttachList; }
            set
            {
                //base.SetProperty<List<A_Annex>>(ref this._diaryAttachList, value);
                if (this._diaryAttachList == value)
                    return;
                this._diaryAttachList = value;
                this.RaisePropertyChanged("DiaryAttachList");
            }
        }

        /// <summary>
        /// 日记内容
        /// </summary>
        public string DiaryXaml
        {
            get { return _diaryXaml; }
            set
            {
                //base.SetProperty<string>(ref this._diaryXaml, value);
                if (this._diaryXaml == value)
                    return;
                this._diaryXaml = value;
                this.RaisePropertyChanged("DiaryXaml");
            }
        }
        /// <summary>
        /// 是否选中回收站
        /// </summary>
        public bool IsSelectedRecycleSite
        {
            get { return _isSelectedRecycleSite; }
            set
            {
                //base.SetProperty<bool>(ref this._isSelectedRecycleSite, value);
                if (this._isSelectedRecycleSite == value)
                    return;
                this._isSelectedRecycleSite = value;
                this.RaisePropertyChanged("IsSelectedRecycleSite");
            }
        }
        /// <summary>
        /// 回收站日记数量
        /// </summary>
        public int RecycleDiaryCount
        {
            get { return _recycleDiaryCount; }
            set
            {
                //base.SetProperty<int>(ref this._recycleDiaryCount, value);
                if (this._recycleDiaryCount == value)
                    return;
                this._recycleDiaryCount = value;
                this.RaisePropertyChanged("RecycleDiaryCount");
            }
        }
        /// <summary>
        /// 日记显示方式
        /// </summary>
        public DiaryDisplay DiaryDisplayMode
        {
            get { return _diaryDisplyMode; }
            set
            {
                //base.SetProperty<DiaryDisplay>(ref this._diaryDisplyMode, value);
                if (this._diaryDisplyMode == value)
                    return;
                this._diaryDisplyMode = value;
                this.RaisePropertyChanged("DiaryDisplayMode");
            }
        }

        /// <summary>树节点</summary>
        public List<TreeNodeViewModel> TreeNodeList { get; set; }
        /// <summary>
        /// 是否显示下拉 的排序列表
        /// </summary>
        //public bool ShowSortMenuItem
        //{
        //    get { return _showSortMenuItem; }
        //    set
        //    {
        //        //base.SetProperty<bool>(ref this._showSortMenuItem, value);
        //        if (this._showSortMenuItem == value)
        //            return;
        //        this._showSortMenuItem = value;
        //        this.RaisePropertyChanged("ShowSortMenuItem");
        //    }
        //}
        /// <summary>
        /// 日记面板右上角是否显示左侧面板图片
        /// </summary>
        public string ShowLeftSPImagePath
        {
            get { return _showLeftSPImagePath; }
            set
            {
                //base.SetProperty<string>(ref this._showLeftSPImagePath, value);
                if (this._showLeftSPImagePath == value)
                    return;
                this._showLeftSPImagePath = value;
                this.RaisePropertyChanged("ShowLeftSPImagePath");
            }
        }
        public string WordCountText
        {
            get { return _wordCountText; }
            set
            {
                //base.SetProperty<string>(ref this._wordCountText, value);
                if (this._wordCountText == value)
                    return;
                this._wordCountText = value;
                this.RaisePropertyChanged("WordCountText");
            }
        }
        /// <summary> 农历日期 </summary>
        public string NowDetailDate
        {
            get { return _nowDetailDate; }
            set
            {
                //base.SetProperty<string>(ref this._nowDetailDate, value);
                if (this._nowDetailDate == value)
                    return;
                this._nowDetailDate = value;
                this.RaisePropertyChanged("NowDetailDate");
            }
        }
        /// 
        /// </summary>
        public A_Diary DiaryModel
        {
            get { return _diaryModel; }
            set
            {
                //base.SetProperty<A_Diary>(ref this._diaryModel, value);

                if (this._diaryModel == value)
                    return;
                this._diaryModel = value;

                if (this._diaryModel != null && this._diaryModel.Content != null)
                {
                    this.WordCountText = CText.Replace(_diaryModel.Content, "<(.*?)>", "").Length.ToString();
                }
                this.RaisePropertyChanged("DiaryModel");
            }
        }
        /// <summary> 确定按钮文本 </summary>
        public string ButtonAcceptText
        {
            get { return _buttonAcceptText; }
            set
            {
                //base.SetProperty<string>(ref this._buttonAcceptText, value);
                if (this._buttonAcceptText == value)
                    return;
                this._buttonAcceptText = value;
                this.RaisePropertyChanged("ButtonAcceptText");
            }
        }
        /// <summary> 左侧面板是否显示 </summary>
        public bool LeftStackPanelShow
        {
            get { return _leftStackPanelShow; }
            set
            {
                //base.SetProperty<bool>(ref this._leftStackPanelShow, value);
                if (this._leftStackPanelShow == value)
                    return;
                this._leftStackPanelShow = value;
                this.RaisePropertyChanged("LeftStackPanelShow");
            }
        }
        /// <summary>
        /// 心情列表 
        /// </summary>
        public List<A_Item> MoodList
        {
            get
            {
                if (_moodList == null || _moodList.Count == 0)
                    LoadMoodList();

                return _moodList;
            }
            set
            {
                //base.SetProperty<List<A_Item>>(ref this._moodList, value);
                if (this._moodList == value)
                    return;
                this._moodList = value;
                this.RaisePropertyChanged("MoodList");
            }
        }
        /// <summary>
        /// 日记列表 
        /// </summary>
        public ObservableCollection<A_Diary> DiaryList
        {
            get
            {
                return _diaryList;
            }
            set
            {
                //base.SetProperty<List<A_Diary>>(ref this._diaryList, value);
                if (this._diaryList == value)
                    return;
                this._diaryList = value;
                this.RaisePropertyChanged("DiaryList");
            }
        }
        /// <summary>
        /// 天气列表 
        /// </summary>
        public List<A_Item> WeatherList
        {
            get
            {
                if (_weatherList == null || _weatherList.Count == 0)
                    LoadWeatherList();
                return _weatherList;
            }
            set
            {
                //base.SetProperty<List<A_Item>>(ref this._weatherList, value);
                if (this._weatherList == value)
                    return;
                this._weatherList = value;
                this.RaisePropertyChanged("WeatherList");
            }
        }
        /// <summary>
        /// 类别（标签） 
        /// </summary>
        public List<A_Item> TypeList { get; set; }
        /// <summary>
        /// 分组（标签） 
        /// </summary>
        public List<A_Item> GroupList { get; set; }
        /// <summary> 日期统计集合 </summary>
        public List<TreeNodeViewModel> DateTreeNodeList
        {
            get { return _dateTreeNodeList; }
            set
            {
                //base.SetProperty<List<TreeNodeViewModel>>(ref this._dateTreeNodeList, value);
                if (this._dateTreeNodeList == value)
                    return;
                this._dateTreeNodeList = value;
                this.RaisePropertyChanged("DateTreeNodeList");
            }
        }
        #endregion

        #region 命令
        /// <summary>保存</summary>
        public ICommand SaveDiaryCommand { get; set; }
        /// <summary>查询</summary>
        public ICommand DiarySearchByInputChangedCommand { get; set; }
        /// <summary></summary>
        public ICommand AddDiaryCommand { get; set; }
        /// <summary>日记列表页面 加载数据 </summary>
        public ICommand ListLoadCommand { get; set; }
        /// <summary>日记编辑页面 加载数据 </summary>
        public ICommand FormLoadCommand { get; set; }
        /// <summary> 日期选择 </summary>
        public ICommand CalendarMouseClickCommand { get; set; }
        /// <summary> 收缩展开 </summary>
        public ICommand ShowOrShrinkLeftSPCommand { get; set; }
        /// <summary> 选择日期 </summary>
        public ICommand SelectedDateChangedCommand { get; set; }
        /// <summary>  </summary>
        public ICommand DiarySelectedChangedCommand { get; set; }
        /// <summary>选中附件</summary>
        public ICommand AttachSelectedChangedCommand { get; set; }
        /// <summary>选择编辑器背景图</summary>
        public ICommand SwitchSkinCommand { get; set; }
        public ICommand ResetCommand { get; set; }
        /// <summary>下拉排序命令</summary>
        public ICommand DiarySortMenuCommand { get; set; }
        /// <summary>搜索</summary>
        public ICommand DiarySearchByInputCommand { get; set; }
        /// <summary>日记列表上下文</summary>
        public ICommand DiaryListContextMenuCommand { get; set; }
        /// <summary>附件列表上下文</summary>
        public ICommand AttachSelectedContextMenuCommand { get; set; }
        /// <summary>回收站</summary>
        public ICommand SelectedRecycleDiaryCommand { get; set; }
        /// <summary>添加附件</summary>
        public ICommand AddAttachFileCommand { get; set; }

        #endregion

        #region 方法
        /// <summary>
        /// 搜索日记列表
        /// </summary>
        private void SearchDiaryList(string title)
        {
            try
            {
                Utils.Helper.Instance.Loading(() =>
                {
                    int recordCount = 0;
                    this.DiaryList = new ObservableCollection<A_Diary>(
                         diaryBLL.GetPageListByHistoryWhere(this.historyWhere + " AND Title LIKE'%" + title + "%' ", 50, 1, null, out recordCount)
                     );
                }, MslDiary.Framework.ShowMessage.SEARCH_MSG01);
            }
            catch (Exception ex)
            {
                MSL.Tool.LogHelper.Instance.WriteLog(ex.ToString());
            }
        }
        /// <summary>
        /// 时间归档查询
        /// </summary>
        private void SearchByDateChanged(object m)
        {
            if (m == null) return;
            if (MFW.Gloable.IsImmediatelyLock) return;
            if (m.ToString().IndexOf("按") > 0) return;
            //日期查询
            if (m is System.Windows.Controls.HeaderedItemsControl)
            {
                string type = ((System.Windows.Controls.HeaderedItemsControl)(m)).Header.ToString();
                GetDiaryListByDate("DiaryDate", type, null);
                return;
            }
            //归档查询
            TreeNodeViewModel node = (TreeNodeViewModel)m;
            this.selectedNodeId = node.ID;

            if (node == null || !node.DisplayName.Contains(" ")) return;
            string month = String.Empty, year = String.Empty;
            string where = String.Empty;
            if (node.ParentID > 0)//月 substr('2014-12-13',0,8)
            {
                if (node.ParentNode != null)
                    year = node.ParentNode.DisplayName.Split(' ')[0];
                month = node.DisplayName.Split(' ')[0];
                where = String.Format(" AND DiaryYear={0} AND DiaryMonth={1} ", year, month);
            }
            else
            {
                year = node.DisplayName.Split(' ')[0];
                where = String.Format(" AND DiaryYear={0} ", year);
            }
            GetDiaryListByDate("DiaryDate", null, where);
        }
        /// <summary>
        /// 初始化 
        /// </summary>
        private void OnInit()
        {
            MSL.Tool.Security.DESEncrypt.Key = Framework.Gloable.DiaryEncryptKey;
            this.DateTreeNodeList = new List<TreeNodeViewModel>();
            this.ResetCommand = new CommandBase((Object m) => Reset(DateTime.Now));

            this.GroupList = itemBLL.GetList(" FatherId=22 ", " Id,Name ", "Id");
            this.TypeList = itemBLL.GetList(" FatherId=21 ", " Id,Name ", "Id");
        }
        /// <summary>
        /// 日记 Xaml 格式内容
        /// </summary>
        private void UpdateDiaryXaml()
        {
            if (this.DiaryModel == null) return;

            this.IsShowAttachButton = false;
            this.IsCheckedAttachButton = false;
            this.DiaryXaml = this.DiaryModel.Content;
            this.NowDetailDate = this.DiaryModel.DiaryDate.ToString("yyyy年MM月dd日 ") + MFW.CanlendarHelper.WeekDayStr(this.DiaryModel.DiaryDate) + " 农历" + MFW.CanlendarHelper.GetChineseDateTime(this.DiaryModel.DiaryDate);
            this.DiaryAttachList = annexBLL.GetDiaryAttachList(this.DiaryModel.Id);
            if (this.DiaryAttachList != null && this.DiaryAttachList.Count > 0)
            {
                this.IsShowAttachButton = true;
                this.IsCheckedAttachButton = true;
            }
            if (!String.IsNullOrEmpty(this.DiaryModel.BackGroundPath))
                this.EditorBackGroundPath = PACK_APPLICATION + "/Theme/Images/EditorSkin/" + this.DiaryModel.BackGroundPath;
            else
                this.EditorBackGroundPath = PACK_APPLICATION + EDITOR_DEFAULT_IMAGE;

        }
        private void CalendarClick(string selectDate)
        {
            if (MFW.Gloable.IsImmediatelyLock) return;
            this.IsSelectedRecycleSite = false;
            this.IsShowAttachButton = false;
            this.IsCheckedAttachButton = false;
            this.DiaryAttachList = null;

            DateTime date;
            if (DateTime.TryParse(selectDate, out date))
            {
                if (date > DateTime.Now.AddMinutes(10))
                {
                    MslDiary.Utils.Helper.Instance.AlertWarning("很抱歉，当前选择日期未到，不能添加日记！");
                    return;
                }
                A_Diary mod = diaryBLL.GetModelByDiaryDate(date);
                if (mod != null && mod.Id != 0)
                {
                    this.DiaryModel = mod;
                    UpdateDiaryXaml();
                    mod = null;
                    this.ButtonAcceptText = "更新";
                }
                else
                    Reset(date);
            }
        }
        /// <summary>
        /// 归档
        /// </summary>
        private void LoadDiaryDateList()
        {
            string tmp;//= "2014-12-20|2014-11-12|2014-10-54|2014-11-64|2014-09-65|2013-12-34|2013-11-4|2013-10-2|2013-11-7|2013-09-8";// diaryBLL.GetCensusByDate();
            tmp = diaryBLL.GetCensusByDate();
            ArrayList al = TreeHelper.GetExpandedId(TreeNodeList);
            TreeNodeList = new List<TreeNodeViewModel>();

            if (tmp != null && tmp.Length > 0)
            {
                this.treeNodeTable = new Hashtable();
                int year = 0, month = 0, num = 0, intTmp = 0, k = 1, parentId = 0;
                foreach (string item in tmp.Split('|'))
                {
                    #region ##

                    year = Int32.Parse(item.Split('-')[0]);
                    month = Int32.Parse(item.Split('-')[1]);
                    num = Int32.Parse(item.Split('-')[2]);
                    if (k == 1)
                    {
                        intTmp = year;
                        TreeNodeList.Add(new TreeNodeViewModel
                        {
                            ID = 1,
                            DisplayName = year.ToString() + " 年",
                            ParentID = 0,
                            IsExpanded = (year == DateTime.Now.Year ? true : false),
                            IsSelected = (this.selectedNodeId != 0 && this.selectedNodeId == 1 ? true : false)
                        });
                        //treeNodeTable.Add(year, 1);
                        k++;
                        TreeNodeList.Add(new TreeNodeViewModel
                        {
                            ID = k,
                            DisplayName = ((month != 11 && month != 12 && month != 10) ? "0" + month.ToString() : month.ToString()) + " 月",
                            Num = num,
                            ParentID = 1,
                            IsSelected = (this.selectedNodeId != 0 && this.selectedNodeId == k ? true : false)
                        });
                        treeNodeTable.Add(year.ToString() + "-" + month.ToString(), k);
                        parentId = 1;
                        k++;
                        continue;
                    }
                    if (intTmp == year)
                    {
                        TreeNodeList.Add(new TreeNodeViewModel
                        {
                            ID = k,
                            DisplayName = ((month != 11 && month != 12 && month != 10) ? "0" + month.ToString() : month.ToString()) + " 月",
                            ParentID = parentId,
                            Num = num,
                            IsExpanded = (al != null && al.Contains(k) ? true : false),
                            IsSelected = (this.selectedNodeId != 0 && this.selectedNodeId == k ? true : false)
                        });
                        treeNodeTable.Add(year.ToString() + "-" + month.ToString(), k);
                    }
                    else
                    {
                        parentId = k;
                        intTmp = year;
                        TreeNodeList.Add(new TreeNodeViewModel
                        {
                            ID = k,
                            DisplayName = year.ToString() + " 年",
                            ParentID = 0,
                            IsExpanded = (al != null && al.Contains(k) ? true : false),
                            IsSelected = (this.selectedNodeId != 0 && this.selectedNodeId == k ? true : false)
                        });
                        k++;
                        TreeNodeList.Add(new TreeNodeViewModel
                        {
                            ID = k,
                            DisplayName = ((month != 11 && month != 12 && month != 10) ? "0" + month.ToString() : month.ToString()) + " 月",
                            ParentID = parentId,
                            Num = num,
                            IsSelected = (this.selectedNodeId != 0 && this.selectedNodeId == k ? true : false)
                        });
                        treeNodeTable.Add(year.ToString() + "-" + month.ToString(), k);
                    }
                    k++;
                    #endregion
                }
                DateTreeNodeList = TreeHelper.Bind(TreeNodeList);
            }
        }
        private void GetDiaryListByDate(string dateFieldName, string type, string where)
        {
            Utils.Helper.Instance.Loading(() =>
             {
                 SearchType searchType = SearchType.All;
                 if (type != null)
                 {
                     if (type.Contains("年"))
                         searchType = SearchType.Year;
                     else if (type.Contains("月"))
                         searchType = SearchType.Month;
                     else if (type.Contains("日"))
                         searchType = SearchType.Day;
                     else if (type.Contains("7"))
                         searchType = SearchType.Lately7Days;
                     else if (type.Contains("30"))
                         searchType = SearchType.Lately30Days;
                     if (String.IsNullOrEmpty(dateFieldName))
                         dateFieldName = "DiaryDate";
                 }
                 GetDiaryList(dateFieldName, searchType, where);
             }, MslDiary.Framework.ShowMessage.SEARCH_MSG01);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">1:列表页加载，2：单独编辑页</param>
        private void Load(string type)
        {
            if (type != null && type.Equals("1"))
            {
            }
            this.annexBLL.DeleteNoSaveDiaryAttach();

            LoadDiaryDateList();
            this.RecycleDiaryCount = diaryBLL.RecycleDiaryCount();

            GetDiaryList(null, SearchType.All, null);
            #region 锁定

            this.timer = new DispatcherTimer();//键盘或鼠标没有操作超过300秒锁定日记本
            this.timer.Interval = TimeSpan.FromSeconds(1);
            this.timer.Tick += LockTimer_Tick;
            this.timer.Start();

            #endregion
        }

        private void LoadWeatherList()
        {
            this.WeatherList = itemBLL.GetList(" FatherId=12 ", " Id,Name,Path ", "Id");
        }
        private void LoadMoodList()
        {
            this.MoodList = itemBLL.GetList(" FatherId=24 ", " Id,Name,Path ", "Id");
        }
        private void GetDiaryList(string dateFieldName, SearchType searchType, string where)
        {
            int recordCount = 0;
            this.DiaryList = new ObservableCollection<A_Diary>(
                //最多显示 100 条
                diaryBLL.GetPageList(dateFieldName, searchType, GetIsDeleteWhere() + where, 100, 1, " DiaryDate DESC ", out recordCount, out historyWhere)
            );
            if (recordCount > 0)
            {
                this.DiaryModel = diaryBLL.GetModelById(this.DiaryList[0].Id);
                UpdateDiaryXaml();
                this.ButtonAcceptText = "更新";
                return;
            }
            Reset(DateTime.Now);
        }
        private string GetIsDeleteWhere()
        {
            return this.IsSelectedRecycleSite ? " AND IsDelete='1' " : " AND IsDelete='0' ";
        }
        private void Save(ArrayList alImage)
        {
            if (MFW.Gloable.IsImmediatelyLock)
            {
                MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.LOCK_MSG03);
                return;
            }
            if (this.DiaryModel == null || String.IsNullOrEmpty(DiaryModel.Title) || String.IsNullOrEmpty(this.DiaryXaml))
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("标题或内容不能为空！");
                return;
            }
            try
            {
                this.DiaryModel.DiaryYear = this.DiaryModel.DiaryDate.Year;
                this.DiaryModel.DiaryMonth = this.DiaryModel.DiaryDate.Month;
                this.DiaryModel.DiaryDay = this.DiaryModel.DiaryDate.Day;
                this.DiaryModel.Content = this.DiaryXaml;
                this.DiaryModel.BackGroundPath = Gloable.EditorBackgroundImage.Substring(Gloable.EditorBackgroundImage.LastIndexOf('/') + 1);

                string summary = MslDiary.Framework.Text.CText.GetTxt(this.DiaryModel.Content);
                summary = " " + (summary.Length > 200 ? summary.Substring(0, 200) : summary);
                this.DiaryModel.Summary = summary;

                //this.currentSelectedId = this.DiaryModel.Id;
                int id = this.DiaryModel.Id;
                if (this.DiaryModel.Id == 0)//新增
                {
                    DiaryModel.CreateDate = DateTime.Now;
                    if (diaryBLL.Add(this.DiaryModel, alImage) > 0)
                    {
                        id = this.diaryBLL.GetMaxId();
                        //this.currentSelectedId = this.diaryBLL.GetMaxId();
                        this.DiaryModel.Id = this.diaryBLL.GetMaxId();
                        MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                        this.DiaryModel.Summary = summary;
                        UpdateDiaryList(this.DiaryModel, true);
                    }
                    else
                        MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                }
                else
                {
                    DiaryModel.ModifyDate = DateTime.Now;
                    if (diaryBLL.Update(this.DiaryModel, " Id=" + DiaryModel.Id, alImage) > 0)
                    {
                        MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                        //更新集合
                        this.DiaryModel.Summary = summary;
                        UpdateDiaryList(this.DiaryModel, false);
                    }
                    else
                        MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                }
                //保存附件
                annexBLL.SaveNoSaveDiaryAttach(id);
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog("DiaryListViewModel Save", ex.ToString());
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.SYS_MSG01);
            }
        }
        /// <summary>
        /// 更新日记集合列表
        /// </summary>
        /// <param name="mod"></param>
        /// <param name="isAdd"></param>
        private A_Diary UpdateDiaryList(A_Diary mod, bool isAdd)
        {
            if (mod == null) return mod;
            mod.AttachNum = annexBLL.DiaryAttachCountByRecordId(mod.Id);
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (isAdd)
                {
                    this.DiaryList.Insert(0, this.DiaryModel);

                    if (mod.DiaryYear == DateTime.Now.Year || mod.DiaryMonth == DateTime.Now.Month)
                        LoadDiaryDateList();
                }
                else
                {
                    int index = RemoveFormDiaryListById(this.DiaryModel.Id);
                    if (index >= 0)
                        this.DiaryList.Insert(index, this.DiaryModel);
                }
            }));
            return mod;
        }
        private void Reset(DateTime diaryDate)
        {
            if (MFW.Gloable.IsImmediatelyLock)
            {
                MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.LOCK_MSG03);
                return;
            }
            this.ButtonAcceptText = "添加";
            this.DiaryModel = new A_Diary()
            {
                Title = "日记 " + diaryDate.ToString("yyyy-MM-dd") + " " + MFW.CanlendarHelper.WeekDayStr(diaryDate).Replace("星期", "周"),
                DiaryDate = diaryDate,
                WeatherId = this.WeatherList[0].Id,
                MoodId = this.MoodList[0].Id
            };
            this.IsShowAttachButton = false;
            this.IsCheckedAttachButton = false;
            this.DiaryAttachList = null;
            this.DiaryXaml = String.Empty;
            this.WordCountText = "0";
            //this.currentSelectedId = 0;
            this.NowDetailDate = diaryDate.ToString("yyyy年MM月dd日 ") + MFW.CanlendarHelper.WeekDayStr(diaryDate) + " 农历" + MFW.CanlendarHelper.GetChineseDateTime(diaryDate);
        }
        private void DiaryListContextClick(string type)
        {
            int result = 0;
            try
            {
                switch (type)
                {
                    case "1"://打印
                        MslDiary.Utils.Helper.Instance.AlertWarning("开发中！");
                        break;
                    case "2"://删除 到 回收站

                        if (MslDiary.Framework.Gloable.IsImmediatelyLock)
                        {
                            MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.LOCK_MSG01);
                            return;
                        }
                        if (this.DiaryModel == null || this.DiaryModel.Id == 0)
                        {
                            MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.DEL_MSG01);
                            return;
                        }
                        MslDiary.Utils.Helper.Instance.AlertConfirm("警告", this.IsSelectedRecycleSite ? ShowMessage.DEL_MSG03 : ShowMessage.DEL_MSG02, () =>
                        {
                            if (this.IsSelectedRecycleSite)
                                TrueDeleteDiaryById(this.DiaryModel.Id);
                            else
                                DeleteDiaryToRecycleSiteById(this.DiaryModel.Id);

                            //this.currentSelectedId = 0;
                        });
                        break;
                    case "3": //导出
                        if (MslDiary.Framework.Gloable.IsImmediatelyLock)
                        {
                            MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.LOCK_MSG01);
                            return;
                        }
                        if (this.DiaryModel == null || this.DiaryModel.Id == 0)
                        {
                            MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.SELECTED_MSG01);
                            return;
                        }
                        SaveFileDialog sfd = new SaveFileDialog
                        {
                            Filter = "数据备份文件(*.htm)|*.htm",
                            RestoreDirectory = true
                        };
                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            string html = this.DiaryModel.Content;
                            MSL.Tool.IOHelper.Instance.WriteFile(sfd.FileName, html);
                        }
                        //Helper.Instance.AlertWarning("开发中！");
                        break;
                    case "4": //恢复
                        if (diaryBLL.RecoveryDiaryById(this.DiaryModel.Id))
                        {
                            MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.RECOVERY_MSG01);
                            LoadDiaryDateList();

                            RemoveFormDiaryListById(this.DiaryModel.Id);
                            this.RecycleDiaryCount = this.RecycleDiaryCount > 0 ? this.RecycleDiaryCount - 1 : 0;
                            //this.currentSelectedId = 0;
                        }
                        else
                            MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                        break;
                    case "5": //全部删除
                        MslDiary.Utils.Helper.Instance.AlertConfirm("警告", ShowMessage.DEL_MSG03, () =>
                        {
                            App.Current.Dispatcher.Invoke(new Action(delegate
                            {
                                result = diaryBLL.ClearRecycle();
                                if (result > 0)
                                {
                                    this.DiaryList.Clear();
                                    this.RecycleDiaryCount = 0;
                                    MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.RECYCLE_MSG01);
                                    //this.currentSelectedId = 0;
                                }
                                else
                                    MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                            }), null);
                        });
                        break;
                    case "6": //全部恢复
                        result = diaryBLL.RecoveryRecycle();
                        if (result > 0)
                        {
                            this.DiaryList.Clear();
                            this.RecycleDiaryCount = 0;
                            MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.RECYCLE_MSG02);
                            LoadDiaryDateList();
                            //this.currentSelectedId = 0;
                        }
                        else
                            MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                        break;
                }
            }
            catch (Exception ex)
            {
                MSL.Tool.LogHelper.Instance.WriteLog("DiaryListContextClick cmClick 运行\r\n" + ex.ToString());
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
            }
        }
        /// <summary>
        /// 附件列表上下文
        /// </summary>
        /// <param name="p"></param>
        private void AttachListContextClick(string p)
        {
            try
            {
                switch (p)
                {
                    case "1"://另存为
                        if (this.SelectedAttachId == 0)
                        {
                            MslDiary.Utils.Helper.Instance.AlertWarning("没有选中附件！");
                            return;
                        }
                        using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
                        {
                            if (System.Windows.Forms.DialogResult.OK == dialog.ShowDialog())
                            {
                                if (annexBLL.SaveAttachById(this.SelectedAttachId, dialog.FileName))
                                    MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.SAVE_MSG01);
                            }
                        }
                        break;
                    case "2"://删除
                        if (this.SelectedAttachId == 0)
                        {
                            MslDiary.Utils.Helper.Instance.AlertWarning("没有选中附件！");
                            return;
                        }
                        MslDiary.Utils.Helper.Instance.AlertConfirm("警告", MslDiary.Framework.ShowMessage.DEL_MSG03, () =>
                         {
                             if (annexBLL.Delete(" Id=" + this.SelectedAttachId) > 0)
                             {
                                 MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                                 this.DiaryAttachList = annexBLL.GetDiaryAttachList(this.DiaryModel.Id);
                                 //RemoveFormDiaryAttachListById(this.SelectedAttachId);
                                 this.DiaryModel.AttachNum = annexBLL.DiaryAttachCountByRecordId(this.DiaryModel.Id);
                                 if (this.DiaryModel.AttachNum == 0 && this.DiaryModel.Id > 0)
                                 {
                                     UpdateDiaryList(this.DiaryModel, false);
                                     this.IsShowAttachButton = false;
                                     this.IsCheckedAttachButton = false;
                                 }
                             }
                             else
                                 MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                         });
                        break;
                }
            }
            catch (Exception ex)
            {
                MSL.Tool.LogHelper.Instance.WriteLog("AttachListContextClick cmClick \r\n" + ex.ToString());
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>移除项索引</returns>
        private int RemoveFormDiaryListById(int id)
        {
            int result = -1;
            if (this.DiaryList != null && this.DiaryList.Count > 0)
            {
                List<A_Diary> list = new List<A_Diary>(this.DiaryList);
                result = list.FindIndex(p => p.Id.Equals(id));
                System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { this.DiaryList.RemoveAt(result); }));
                return result;
                //int n = list.FindIndex(new Predicate<A_Diary>((p) =>
                //{
                //    return p.Id.Equals(id);
                //}));
            }
            return result;

        }

        /// <summary>
        /// 删除到回收站
        /// </summary>
        /// <param name="id"></param>
        private void DeleteDiaryToRecycleSiteById(int id)
        {
            this.DiaryModel.IsDelete = "1";
            int result = diaryBLL.Update(this.DiaryModel, " Id=" + id);
            if (result > 0)
            {
                RemoveFormDiaryListById(this.DiaryModel.Id);
                MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                this.RecycleDiaryCount = this.RecycleDiaryCount + 1;

                string date = this.DiaryModel.DiaryYear + "-" + this.DiaryModel.DiaryMonth;
                TreeNodeViewModel node = TreeHelper.FindNodeById(this.TreeNodeList, Int32.Parse(treeNodeTable[date].ToString()));
                if (node != null)
                {
                    if (node.Num == 1)
                    {
                        this.TreeNodeList.Remove(node);
                        LoadDiaryDateList();
                    }
                    else
                    {
                        node.Num = node.Num - 1;
                    }
                }
            }
            else
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
        }
        private void TrueDeleteDiaryById(int id)
        {
            int result = diaryBLL.Delete(" Id=" + id);
            if (result > 0)
            {
                RemoveFormDiaryListById(this.DiaryModel.Id);
                MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                this.RecycleDiaryCount = this.RecycleDiaryCount > 0 ? this.RecycleDiaryCount - 1 : 0;
            }
            else
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
        }
        private void LockTimer_Tick(object sender, EventArgs e)
        {
            if (MslDiary.Framework.Gloable.IsEditorSkinChanged)
            {
                this.EditorBackGroundPath = PACK_APPLICATION + MslDiary.Framework.Gloable.EditorBackgroundImage;
                MslDiary.Framework.Gloable.IsEditorSkinChanged = false;
            }
            if (Gloable.DiaryIsLock)
            {
                if (
                    (MFW.Gloable.IsImmediatelyLock || MslDiary.Utils.Helper.Instance.GetIdleTick() / 1000 > MFW.Gloable.LeaveTimeToLock)
                    && this.DiaryDisplayMode != DiaryDisplay.LockDiaryListTemplate
                    )
                {
                    MslDiary.Framework.Gloable.IsImmediatelyLock = true;
                    this.DiaryDisplayMode = DiaryDisplay.LockDiaryListTemplate;
                    MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.LOCK_MSG03);
                    MslDiary.Utils.Helper.Instance.ClearCachFile();//清空缓存 避免秘密文件被别人看到
                    return;
                }
            }
            if (!MslDiary.Framework.Gloable.IsImmediatelyLock && this.DiaryDisplayMode == DiaryDisplay.LockDiaryListTemplate)
            {
                this.DiaryDisplayMode = DiaryDisplay.Summary;
            }
        }
        #endregion
    }
}